import JSZip from '@ohos/jszip';
import StreamBuf from './stream-buf';
import { LogUtil } from '../utils/log-util'

// The ZipWriter class
// Packs streamed data into an output zip stream
class ZipWriter {
    constructor(options) {
        this.options = Object.assign(
            {
                type: 'arraybuffer',
                compression: 'DEFLATE',
            },
            options
        );
        this.zip = new JSZip();
        this.stream = new StreamBuf();
    }

    append(data, options) {
        if (options?.base64) {
            this.zip.file(options.name, data, { base64: true });
        } else {
            this.zip.file(options.name, data);
        }
    }

    async finalize() {
        try {
            const content = await this.zip.generateAsync(this.options);
            this.stream.end(content);
        } catch (e) {
            LogUtil.error(e);
        }
    }

    // Stream.Readable interface
    read(size) {
        return this.stream.read(size);
    }

    setEncoding(encoding) {
        return this.stream.setEncoding(encoding);
    }

    pause() {
        return this.stream.pause();
    }

    resume() {
        return this.stream.resume();
    }

    isPaused() {
        return this.stream.isPaused();
    }

    pipe(destination, options) {
        return this.stream.pipe(destination, options);
    }

    unpipe(destination) {
        return this.stream.unpipe(destination);
    }

    unshift(chunk) {
        return this.stream.unshift(chunk);
    }

    wrap(stream) {
        return this.stream.wrap(stream);
    }
}


export default {
    ZipWriter
};
